package db

import (
	"fmt"
	"gif_project/models"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
)

const (
	dataSource          = "root:12345678@tcp(127.0.0.1:3306)/gif?charset=utf8"
	articleTable        = "t_article_list"
	articleDetailsTable = "t_article_details"
)

var globalDB *gorm.DB

type ArticleListItem struct {
	ID                   int    `gorm:"AUTO_INCREMENT;primary_key;column:id" json:"id"`
	ArticleId            int    `gorm:"column:article_id;not null;unique" json:"articleId"`
	TypeName             string `gorm:"size:45;column:type_name" json:"typeName"`
	ArticleImg           string `gorm:"size:200;column:article_img" json:"articleImg"`
	ArticleTitle         string `gorm:"size:100;column:article_title" json:"articleTitle"`
	ArticleDetailsSrc    string `gorm:"size:200;column:article_detailsSrc" json:"articleDetailsSrc"`
	ArticleImgCount      int    `gorm:"column:article_imgCount" json:"articleImgCount"`
	ArticleSendTime      int    `gorm:"column:article_sendTime" json:"articleSendTime"`
	ArticleAuthor        string `gorm:"size:45;column:article_author" json:"articleAuthor"`
	ArticleReadCount     int    `gorm:"column:article_readCount" json:"articleReadCount"`
	ArticleCommentsCount int    `gorm:"column:article_commentsCount" json:"articleCommentsCount"`
	ArticleLikeCount     int    `gorm:"column:article_likeCount" json:"articleLikeCount"`
	ArticleNote          string `gorm:"size:500;column:article_note" json:"articleNote"`
	ArticleTag           string `gorm:"size:300;column:article_tag" json:"articleTag"`
	CreateTime           int    `gorm:"column:createTime" json:"createTime"`
}

type ArticleDetails struct {
	ID          int    `gorm:"AUTO_INCREMENT;primary_key;column:id" json:"id"`
	ArticleId   int    `gorm:"column:article_id;not null" json:"articleId"`
	ArticleImg  string `gorm:"size:200;column:article_img" json:"articleImg"`
	ArticleText string `gorm:"type:text;column:article_text" json:"articleText"`
	CreateTime  int    `gorm:"column:createTime" json:"createTime"`
}

func (ArticleListItem) TableName() string {
	return articleTable
}

func (ArticleDetails) TableName() string {
	return articleDetailsTable
}

func init() {
	db, err := gorm.Open("mysql", dataSource)
	if err != nil {
		fmt.Println("init OpenDB err")
	}
	if db.HasTable(ArticleListItem{}) != true {
		db.CreateTable(ArticleListItem{})
	}
	if db.HasTable(ArticleDetails{}) != true {
		db.CreateTable(ArticleDetails{})
	}
	globalDB = db
	//globalDB.LogMode(true)
}

func GetArticleWithPage(pageNo int, pageSize int) (page models.Page, err error) {
	var articleList []ArticleListItem
	var totalCount int
	db := globalDB
	db.Table(articleTable).
		Order("article_sendTime DESC").
		Limit(pageSize).
		Offset((pageNo - 1) * pageSize).
		Find(&articleList)
	db.Table(articleTable).
		Count(&totalCount)
	//在爬虫修复
	//for rows.Next() {
	//	var articleItem ArticleListItem
	//	var articleDetails ArticleDetails
	//	err := db.ScanRows(rows, &articleItem)
	//	if err == nil {
	//		//列表图片爬下来有问题，去详情查图赋值
	//		db.Table(articleDetailsTable).
	//			Where("article_id = ? and article_img <> ''", articleItem.ArticleId).
	//			Find(&articleDetails)
	//		articleItem.ArticleImg = articleDetails.ArticleImg
	//	}
	//	articleList = append(articleList, articleItem)
	//}
	page.TotalCount = totalCount
	page.PageNo = pageNo
	page.PageSize = pageSize
	page.List = articleList
	return page, err
}

func GetArticleDetailWithPage(pageNo int, pageSize int, articleId int) (page models.Page, err error) {
	var articleDetails []ArticleDetails
	var totalCount int
	db := globalDB
	db.Table(articleDetailsTable).
		Where("article_id = ?", articleId).
		Order("createTime ASC").
		Limit(pageSize).
		Offset((pageNo - 1) * pageSize).
		Find(&articleDetails)
	db.Table(articleDetailsTable).
		Where("article_id = ?", articleId).
		Count(&totalCount)
	page.TotalCount = totalCount
	page.PageNo = pageNo
	page.PageSize = pageSize
	page.List = articleDetails
	return page, err
}

func GetArticleGroupByType() (types []models.GroupType) {
	var groupTypes []models.GroupType
	db := globalDB
	db.Table(articleTable).
		Select("type_name, count(1) as total_count").
		Group("type_name").
		Order("total_count DESC").
		Find(&groupTypes)
	return groupTypes
}

func GetArticleGroupByTypePage(pageNo int, pageSize int, typeName string) (page models.Page, err error) {
	var articleList []ArticleListItem
	var totalCount int
	db := globalDB
	db.Table(articleTable).
		Where("type_name = ?", typeName).
		Order("article_sendTime DESC").
		Limit(pageSize).
		Offset((pageNo - 1) * pageSize).
		Find(&articleList)
	db.Table(articleTable).
		Where("type_name = ?", typeName).
		Count(&totalCount)
	//在爬虫修复
	//for rows.Next() {
	//	var articleItem ArticleListItem
	//	var articleDetails ArticleDetails
	//	err := db.ScanRows(rows, &articleItem)
	//	if err == nil {
	//		//列表图片爬下来有问题，去详情查图赋值
	//		db.Table(articleDetailsTable).
	//			Where("article_id = ? and article_img <> ''", articleItem.ArticleId).
	//			Find(&articleDetails)
	//		articleItem.ArticleImg = articleDetails.ArticleImg
	//	}
	//	articleList = append(articleList, articleItem)
	//}
	page.TotalCount = totalCount
	page.PageNo = pageNo
	page.PageSize = pageSize
	page.List = articleList
	return page, err
}
